Java Performance by Scott Oaks
Lazy Initialization Runtime Performance
The usual performance penalty for checking whether lazily initialized variables have been initialized may not always exist. Consider this example from the JDK’s ArrayList class. That class maintains an array of the elements it stores, and in older versions of Java, pseudocode for the class looked like this:
public class ArrayList { private Object[] elementData = new Object[16]; int index = 0; public void add(Object o) { ensureCapacity(); elementData[index++] = o; } private void ensureCapacity() { if (index == elementData.length) { ...reallocate array and copy old data in... } } }
A few years ago, this class was changed so that the elementData array is initialized lazily. But because the ensureCapacity() method already needed to check the array size, the common methods of the class didn’t suffer a performance penalty: the code to check for initialization is the same as the code to check whether the array size needs to be increased. The new code uses a static, shared, zero-length array so that performance is the same: